package ustc.xiaoyang.karl.doublepointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 18.四数之和 medium
 */
public class TheSumOfFourNumbers18 {
    public static void main(String[] args) {

    }
    public static List<List<Integer>> fourSum(int[] nums, int target){
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            //一级剪枝去重
            if(nums[i] > target && nums[i] >= 0) break;
            if(i>0 && nums[i] == nums[i-1]) continue;

            for (int j = i+1; j < nums.length; j++) {
                //二级剪枝去重
                if (nums[i] + nums[j] > target && nums[j] + nums[i] >= 0) {
                    break;
                }

                if(j > i+1 && nums[j] == nums[j-1]) continue;
                int left = j+1;
                int right = nums.length-1;
                while (left < right){
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if(sum == target){
                        res.add(List.of(nums[i],nums[j],nums[left],nums[right]));
                        //第三重去重，这段代码很重要，不能遗漏
                        while (right > left && nums[right] == nums[right - 1]) right--;
                        while (right > left && nums[left] == nums[left + 1]) left++;
                        left++;
                        right--;
                    }else if (sum < target){
                        left++;
                    } else right--;
                }
            }
        }
        return res;

    }
}
